package edu.neu.swc.cloud.controller;

import com.alibaba.fastjson.JSON;
import edu.neu.swc.cloud.domain.ProductCata;
import edu.neu.swc.cloud.domain.QueryInfo;
import edu.neu.swc.cloud.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/productType")
public class ProductCateController {

    @Autowired
    CategoryService categoryService;

    @RequestMapping("/allProductTypeList")
    public String list(){
        List<ProductCata> productTypeList = categoryService.findAllPro();

        HashMap<String,Object> res = new HashMap<>();
        res.put("data",productTypeList);
        System.out.println(productTypeList);
        return JSON.toJSONString(res);
    }

    @RequestMapping("/productTypeList")
    public String productTypeList(QueryInfo queryInfo){
        int numbers = categoryService.getProductTypeCounts("%"+queryInfo.getQuery()+"%");
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<ProductCata> productTypeList = categoryService.findProductTypeByQuery("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
        HashMap<String,Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",productTypeList);
        System.out.println("总条数："+numbers);
        System.out.println(productTypeList);
        return JSON.toJSONString(res);
    }

    @RequestMapping("/addProductType")
    public String addProductType(@RequestBody ProductCata productCata){
        String status;
        ProductCata target = categoryService.findProCateByName(productCata.getPro_ca_name());
        if(target == null){
            //类别名称不重复，可以直接添加
            categoryService.addProCate(productCata);
            status = "success";
        }else{
            status = "error";
        }
        return status;
    }

    @RequestMapping("/getUpdate")
    public String getUpdate(int id){
        ProductCata productCata = categoryService.findProCateById(id);
        return JSON.toJSONString(productCata);
    }

    @RequestMapping("/editProductType")
    public String editProductType(@RequestBody ProductCata productCata){
        categoryService.updateProCate(productCata);
        return "success";
    }

    @RequestMapping("/deleteProductType")
    public String deleteProductType(int id){
        categoryService.deleteProCateById(id);
        return "success";
    }



}
